package com.weiwei.diancan.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.google.gson.Gson;
import com.weiwei.diancan.Contant.ConfigMethod;
import com.weiwei.diancan.R;
import com.weiwei.diancan.adapter.HasOrderAdapter;
import com.weiwei.diancan.base.BaseActivity;
import com.weiwei.diancan.bean.LoginBean;
import com.weiwei.diancan.bean.SelectOrder;
import com.weiwei.diancan.cache.CacheConfig;
import com.weiwei.diancan.http.RetrofitFactory;
import com.weiwei.diancan.utils.ActivityManager;
import com.weiwei.diancan.utils.HttpUtils;
import com.weiwei.diancan.utils.LoggerUtils;
import com.weiwei.diancan.utils.OnSuccessListener;
import com.weiwei.diancan.view.EmptyLayout;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import weiwei.com.weiweilibrary.views.ToastUtil;

public class HasOrderActivity extends BaseActivity {

    private RecyclerView recycler;
    private HasOrderAdapter adapter;
    private ArrayList<SelectOrder> selectOrders;
    private String tab_name;
    private String num;
    private String tab_id;
    private TextView tv_shanchu;
    private TextView tv_shangchuan;
    private LoginBean.TypeListBean.TabListBean tabListBean;
    private TextView tv_caipin;
    private TextView tv_shuliang;
    private TextView tv_jiage;
    private DecimalFormat df;
    private EmptyLayout emplety;

    @Override
    public void getData() {
        int all = 0;
        int num = 0;
        double price = 0;
        for(SelectOrder selectOrder:selectOrders){
            double log_count = Double.parseDouble(selectOrder.getLog_count());
            double log_price = Double.parseDouble(selectOrder.getLog_price());
            num+=log_count;
            price+=log_price*log_count;
        }
        all+=selectOrders.size();

        List<LoginBean.OrderListBean> order_list = tabListBean.getOrder_list();
        if(order_list!=null){
            for(LoginBean.OrderListBean orderListBean:order_list){
                List<LoginBean.OrderListBean.LogListBean> log_list = orderListBean.getLog_list();
                if(log_list!=null){
                    for(LoginBean.OrderListBean.LogListBean logListBean:log_list){
                        double log_count = Double.parseDouble(logListBean.getLog_count());
                        double log_price = Double.parseDouble(logListBean.getLog_price());
                        num+=log_count;
                        price+=log_price*log_count;
                    }
                    all+=log_list.size();
                }
            }
        }

        tv_caipin.setText(all+"");
        tv_shuliang.setText(num+"");
        if(price == 0){
            tv_jiage.setText("¥0.00");
        }else {
            tv_jiage.setText("¥"+df.format(price));
        }
    }

    @Override
    public void setListeners() {
        tv_shangchuan.setOnClickListener(v->{
            if(num.equals("-1")) {  //追加订单
                zhuijia();
            }else{                  //上传主订单
                shangchuan();
            }
        });

        tv_shanchu.setOnClickListener(v->{
            EventBus.getDefault().post("diandan");
            List<List> list = new ArrayList<>();
            selectOrders = new ArrayList<SelectOrder>();
            list.add(selectOrders);

            int all = 0;
            int num = 0;
            double price = 0;
            List<LoginBean.OrderListBean> order_list = tabListBean.getOrder_list();
            if(order_list!=null){
                for(LoginBean.OrderListBean orderListBean:order_list){
                    List<LoginBean.OrderListBean.LogListBean> log_list = orderListBean.getLog_list();
                    if(log_list!=null){
                        for(LoginBean.OrderListBean.LogListBean logListBean:log_list){
                            double log_count = Double.parseDouble(logListBean.getLog_count());
                            double log_price = Double.parseDouble(logListBean.getLog_price());
                            num+=log_count;
                            price+=log_price*log_count;
                        }
                        list.add(log_list);
                        all+=log_list.size();
                    }
                }
            }
            if(list.size() == 1){
                emplety.setErrorType(EmptyLayout.NO_DATA,EmptyLayout.NOT_DATA);
            }else{
                emplety.setErrorType(EmptyLayout.HIDE_LAYOUT,EmptyLayout.NOT_DATA);
            }
            adapter = new HasOrderAdapter(list,this,selectOrders);
            recycler.setAdapter(adapter);
            tv_caipin.setText(all+"");
            tv_shuliang.setText(num+"");
            if(price == 0){
                tv_jiage.setText("¥0.00");
            }else {
                tv_jiage.setText("¥"+df.format(price));
            }
        });

    }

    @Override
    public void initView() {
        df = new java.text.DecimalFormat("#.00");

        tv_caipin = (TextView)findViewById(R.id.tv_caipin);
        tv_shuliang = (TextView)findViewById(R.id.tv_shuliang);
        tv_jiage = (TextView)findViewById(R.id.tv_jiage);
        recycler = (RecyclerView)findViewById(R.id.recycler);
        recycler.setLayoutManager(new LinearLayoutManager(this));
        tv_shanchu = (TextView)findViewById(R.id.tv_shanchu);
        tv_shangchuan = (TextView)findViewById(R.id.tv_shangchuan);
        emplety = (EmptyLayout)findViewById(R.id.emptyLayout);

        List<List> list = new ArrayList<>();
        list.add(selectOrders);
        if(tabListBean.getOrder_list()!=null){
            for(int i = 0;i<tabListBean.getOrder_list().size();i++){
                List<LoginBean.OrderListBean.LogListBean> log_list = tabListBean.getOrder_list().get(i).getLog_list();
                list.add(log_list);
            }
        }

        if(list.size() == 1&&selectOrders.size() == 0){
            emplety.setErrorType(EmptyLayout.NO_DATA,EmptyLayout.NOT_DATA);
        }else{
            emplety.setErrorType(EmptyLayout.HIDE_LAYOUT,EmptyLayout.NOT_DATA);
        }

        adapter = new HasOrderAdapter(list,this,selectOrders);
        adapter.setTv_caipin(tv_caipin);
        adapter.setTv_jiage(tv_jiage);
        adapter.setTv_shuliang(tv_shuliang);
        recycler.setAdapter(adapter);
    }

    @Override
    public void initTitle() {
        titler.setText("已选订单("+tab_name+")");

        iv_left.setVisibility(View.VISIBLE);
        iv_left.setText("返回");
        iv_left.setOnClickListener((v)->finish());

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.getInstance().popOneActivity(this);
    }

    @Override
    public void setLayoutView() {
        setContentView(R.layout.activity_has_order);
        ActivityManager.getInstance().pushOneActivity(this);
        Bundle bundle = getIntent().getExtras();
        if(bundle!=null){
            num = bundle.getString("num");
            tabListBean = (LoginBean.TypeListBean.TabListBean)bundle.getSerializable("tabListBean");
            selectOrders = bundle.getParcelableArrayList("selectList");
            tab_name = tabListBean.getTab_name();
            tab_id = tabListBean.getTab_id();
        }
    }

    /**
     * 追加订单
     */
    private void zhuijia(){

        if(adapter.getIsSelectOrder().size() == 0){
            ToastUtil.showToast(this,"请选择菜品后提交订单!");
            return;
        }

        progressDialog.setMessage("订单上传中...");
        progressDialog.show();
        Gson gson = new Gson();
        String order_json = gson.toJson(adapter.getIsSelectOrder());
        Map<String, String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token, CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token, CacheConfig.getInst().getWaterToken(this));
        map.put(ConfigMethod.order_no,tabListBean.getOrder_list().get(0).getOrder_no());
        map.put(ConfigMethod.order_json,order_json);
        RetrofitFactory.getIntance().addOrderGo(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        progressDialog.cancel();
                        HttpUtils.check(loginBean, HasOrderActivity.this, loginBean1 -> {
                            //ActivityManager.getInstance().finishAllActivity();
                            EventBus.getDefault().post("refrsh");
                            EventBus.getDefault().post("zhuidan");
                            finish();
                            //ActivityManager.getInstance().finishAllActivity();
                        });
                    }
                });
    }

    /**
     * 上传订单
     */
    private void shangchuan(){
        if(selectOrders.size() == 0){
            ToastUtil.showToast(this,"请选择菜品后提交订单!");
            return;
        }
        progressDialog.setMessage("订单上传中...");
        progressDialog.show();
        Gson gson = new Gson();
        String order_json = gson.toJson(selectOrders);
        Map<String, String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token, CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token, CacheConfig.getInst().getWaterToken(this));
        map.put(ConfigMethod.table_id,tab_id);
        map.put(ConfigMethod.order_person, num);
        map.put(ConfigMethod.order_json,order_json);
        RetrofitFactory.getIntance().addOrder(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                        e.printStackTrace();
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        progressDialog.cancel();
                        HttpUtils.check(loginBean, HasOrderActivity.this, loginBean1 -> {
                            ActivityManager.getInstance().finishAllActivity();
                            //EventBus.getDefault().post("diandan");
                        });
                    }
                });
    }
}
